import React from "react";
import { useState } from "react";
import { PageHeader, PersonalInfoItem } from "@/components";
import { Card, Image, Upload, Modal, Form, Input, Button, message } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { formatDate } from "@/utils/tools";
import { PlusOutlined } from "@ant-design/icons";
import { updateUserInfoAsync, changeLoginStatus, clearUserInfo } from "@/redux/userSlice";
import styles from "./Personal.module.css";
import { checkPassword } from "@/api/user";
import { useNavigate } from "react-router-dom";
export default function Personal() {
  const { userInfo } = useSelector((state) => state.user);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [panelName, setPanelName] = useState("");
  const [form] = Form.useForm();
  const [passwordInfo, setPasswordInfo] = useState({
    oldpassword: "",
    newpassword: "",
    passwordConfirm: "",
  });

  // 理解 PUT 和 PATCH 请求的区别
  //  -> PUT 请求需要将所有的值都发送给后端
  //  -> PATCH 请求只需要把某一项发送给后端
  // 在这里的体现：如果用户修改了QQ -> editInfo{qq: "123456"} 不是所有的信息
  const [editInfo, setEditInfo] = useState({});

  const showModal = (name) => {
    setPanelName(name);
    setEditInfo({});
    form.resetFields(); // 清空内容 -> 在有 initialValues 的清空下，setEditInfo({}); 这种好像不管用
    setIsModalOpen(true);
  };
  const handleOk = () => {
    // editInfo -> 存储着除密码之外的被修改后的信息
    // 更新数据 -> 仓库和数据库
    dispatch(updateUserInfoAsync({ userId: userInfo._id, newInfo: editInfo }));
    message.success("修改信息成功");
    setIsModalOpen(false);
    // 退出登录
    localStorage.removeItem("token");
    dispatch(clearUserInfo());
    dispatch(changeLoginStatus(false));
    navigate("/");
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 修改头像
  const handleAvatar = (url, key) => {
    // [key]: url -> 动态生成对象的key值
    // 如果直接写成 key: url 那么key直接当作对象的key值，不会解析成参数
    dispatch(updateUserInfoAsync({ userId: userInfo._id, newInfo: { [key]: url } }));
    message.success("修改头像成功");
  };

  // 更新密码
  const updatePasswordInfo = (oldInfo, key) => {
    let newInfo = { ...passwordInfo };
    newInfo[key] = oldInfo.trim();
    setPasswordInfo(newInfo);
    if (key === "newpassword") {
      updateEditInfo(oldInfo, "loginPwd");
    }
  };

  // 确认输入的密码是否正确
  const checkedPasswordIsRight = async () => {
    if (!passwordInfo.oldpassword) {
      return Promise.resolve();
    }
    const { data } = await checkPassword(userInfo._id, passwordInfo.oldpassword);
    if (!data) {
      return Promise.reject("密码错误");
    }
  };

  // 更新修改的信息
  const updateEditInfo = (oldInfo, key) => {
    if (key === "nickname" && !oldInfo) {
      message.warning("昵称不能为空");
      return;
    }
    const newUserInfo = { ...editInfo };
    newUserInfo[key] = oldInfo;
    setEditInfo(newUserInfo);
  };

  let modalContent = null;
  switch (panelName) {
    case "基本信息":
      modalContent = (
        <Form
          form={form}
          name="basic1"
          autoComplete="off"
          initialValues={userInfo}
          onFinish={handleOk}
        >
          <Form.Item
            label="登录密码"
            name="oldpassword"
            rules={[
              { required: true },
              {
                validator: checkedPasswordIsRight,
              },
            ]}
            validateTrigger="onBlur"
          >
            <Input.Password
              value={passwordInfo.oldpassword}
              placeholder="若要修改密码，请先输入旧密码"
              onChange={(e) => updatePasswordInfo(e.target.value, "oldpassword")}
            />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newpassword"
            rules={[
              ({ getFieldValue }) => ({
                validator: (_, value) => {
                  if (value && value.length < 6) {
                    return Promise.reject("密码长度需要大于6位");
                  } else if (value && value === getFieldValue("oldpassword")) {
                    return Promise.reject("新密码不能和旧密码一样");
                  } else return Promise.resolve();
                },
              }),
            ]}
            validateTrigger="onBlur"
          >
            <Input.Password
              value={passwordInfo.newpassword}
              placeholder="请输入新密码"
              onChange={(e) => updatePasswordInfo(e.target.value, "newpassword")}
            />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="passwordConfirm"
            rules={[
              // getFieldValue 接收Form的上下文对象
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("newpassword") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次密码不一致"));
                },
              }),
            ]}
            validateTrigger="onBlur"
          >
            <Input.Password
              value={passwordInfo.passwordConfirm}
              placeholder="请再次输入新密码"
              onChange={(e) => updatePasswordInfo(e.target.value, "passwordConfirm")}
            />
          </Form.Item>

          <Form.Item
            label="用户昵称"
            name="nickname"
            rules={[
              {
                message: "Please input your username!",
              },
            ]}
          >
            <Input
              value={userInfo.nickname}
              placeholder="默认为新用户123456"
              onBlur={(e) => updateEditInfo(e.target.value, "nickname")}
            />
          </Form.Item>

          <Form.Item label={null}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: "90px", marginRight: "20px" }}
            >
              确认
            </Button>
            <Button type="default" htmlType="reset">
              重置
            </Button>
          </Form.Item>
        </Form>
      );

      break;
    case "社交账号":
      modalContent = (
        <Form
          form={form}
          name="basic2"
          autoComplete="off"
          initialValues={userInfo}
          onFinish={handleOk}
        >
          <Form.Item label="邮箱" name="mail">
            <Input
              value={userInfo.mail}
              placeholder="请输入邮箱"
              onChange={(e) => updateEditInfo(e.target.value, "mail")}
            />
          </Form.Item>

          <Form.Item label="QQ号" name="qq">
            <Input
              value={userInfo.qq}
              placeholder="请输入QQ号"
              onChange={(e) => updateEditInfo(e.target.value, "qq")}
            />
          </Form.Item>

          <Form.Item label="微信号" name="wechat">
            <Input
              value={userInfo.wechat}
              placeholder="请输入微信号"
              onChange={(e) => updateEditInfo(e.target.value, "wechat")}
            />
          </Form.Item>

          <Form.Item label="github" name="github">
            <Input
              value={userInfo.github}
              placeholder="请输入GitHub账号"
              onChange={(e) => updateEditInfo(e.target.value, "github")}
            />
          </Form.Item>

          <Form.Item label={null}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: "90px", marginRight: "20px" }}
            >
              确认
            </Button>
            <Button type="default" htmlType="reset">
              重置
            </Button>
          </Form.Item>
        </Form>
      );
      break;
    case "个人简介":
      modalContent = (
        <Form form={form} initialValues={userInfo} autoComplete="off" onFinish={handleOk}>
          <Form.Item label="自我介绍" name="intro">
            <Input.TextArea
              rows={6}
              value={userInfo.intro}
              placeholder="选填"
              onChange={(e) => updateEditInfo(e.target.value, "intro")}
            />
          </Form.Item>

          {/* 确认修改按钮 */}
          <Form.Item wrapperCol={{ offset: 5, span: 16 }}>
            <Button type="primary" htmlType="submit" style={{ marginRight: "20px" }}>
              确认
            </Button>

            <Button type="default" htmlType="submit">
              重置
            </Button>
          </Form.Item>
        </Form>
      );
      break;
  }

  return (
    <>
      <PageHeader title="个人中心" />
      <div className={styles.container}>
        {/* 详细信息 */}
        <div className={styles.row}>
          <Card
            title="基本信息"
            extra={
              <div className={styles.edit} onClick={() => showModal("基本信息")}>
                编辑
              </div>
            }
          >
            <PersonalInfoItem info={{ itemName: "登录账号", itemValue: userInfo.loginId }} />
            <PersonalInfoItem info={{ itemName: "账号密码", itemValue: "***** **** ****" }} />
            <PersonalInfoItem info={{ itemName: "用户昵称", itemValue: userInfo.nickname }} />
            <PersonalInfoItem info={{ itemName: "用户积分", itemValue: userInfo.points }} />
            <PersonalInfoItem
              info={{ itemName: "注册时间", itemValue: formatDate(userInfo.registerDate) }}
            />
            <PersonalInfoItem
              info={{ itemName: "上次登录时间", itemValue: formatDate(userInfo.lastLoginDate) }}
            />
            <div style={{ fontWeight: "100", height: "50px" }}>当前头像</div>
            <Image src={userInfo.avatar} width={100} />
            <div style={{ fontWeight: "100", height: "50px", lineHeight: "50px", margin: "5px" }}>
              上传新头像
            </div>
            <Upload
              action="/api/upload"
              listType="picture-card"
              maxCount={1}
              onChange={(e) => {
                if (e.file.status === "done") {
                  // 说明上传完毕
                  const url = e.file.response.data;
                  // 处理用户头像的更新
                  handleAvatar(url, "avatar");
                }
              }}
            >
              <PlusOutlined />
            </Upload>
          </Card>
        </div>
        {/* 社交账号 */}
        <div className={styles.row}>
          <Card
            title="社交账号"
            extra={
              <div className={styles.edit} onClick={() => showModal("社交账号")}>
                编辑
              </div>
            }
          >
            <PersonalInfoItem
              info={{ itemName: "邮箱", itemValue: userInfo.mail ? userInfo.mail : "未填写" }}
            />
            <PersonalInfoItem
              info={{ itemName: "QQ号", itemValue: userInfo.qq ? userInfo.qq : "未填写" }}
            />
            <PersonalInfoItem
              info={{ itemName: "微信号", itemValue: userInfo.wechat ? userInfo.wechat : "未填写" }}
            />
            <PersonalInfoItem
              info={{ itemName: "github", itemValue: userInfo.github ? userInfo.github : "未填写" }}
            />
          </Card>
        </div>
        {/* 个人简介 */}
        <div className={styles.row}>
          <Card
            title="个人简介"
            extra={
              <div className={styles.edit} onClick={() => showModal("个人简介")}>
                编辑
              </div>
            }
          >
            {userInfo.intro ? userInfo.intro : "未填写"}
          </Card>
        </div>

        <Modal
          title={panelName}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
        >
          {modalContent}
        </Modal>
      </div>
    </>
  );
}
